package com.kcht.itsed.mws.aleframework.specmanage;


import lombok.extern.slf4j.Slf4j;

/**
 * 固定周期的边界条件
 * 通过repeatPeriod和duration两个参数初始化
 * 单位毫秒
 * @author zhangwenshuo
 *
 */
@Slf4j
public class FixedReportPeriodBoundaryCondition implements IBoundaryConditionScheduler {

	private long repeatPeriod, duration;
	
	private boolean running = true;
	private boolean initiationCondition,terminationCondition;
	
	private final Object stateLock = new Object();
	
	private Thread timerThread = new Thread() {
		@Override
		public void run() {
			while(running) {
				try {
					synchronized(stateLock) {
						initiationCondition = true;
					}
				Thread.sleep(duration);
					synchronized(stateLock) {
						terminationCondition = true;
					}
					Thread.sleep(repeatPeriod - duration);
				}catch(Exception e) {
					log.error("",e);
				}
				
			}
		};
	};
	
	
	public FixedReportPeriodBoundaryCondition(long repeatPeriod, long duration) {
		this.repeatPeriod = repeatPeriod;
		this.duration = duration;
		timerThread.start();
	}

	
	@Override
	public boolean initiationConditionSatisfied() {
		synchronized(stateLock) {
			if(initiationCondition) {
				initiationCondition = false;
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean terminationConditionSatisfied() {
		synchronized(stateLock) {
			if(terminationCondition) {
				terminationCondition = false;
				return true;
			}
		}
		return false;
	}

	@Override
	public void stopBoundaryCondition() {
		running = false;
	}
	
	
	

}
